<template>
    <tui-drawer
      mode="bottom"
      :maskZIndex="999990"
      :zIndex="999999"
      :visible="visible"
      @close="closeDrawer"
    >
      <view class="container">
        <view class="form_my">
            <view class="item_info">
            <view class="label_info">{{tutorServiceTitle}}(温馨提示：注意环境干净，服装整洁)</view>
            <view class="comp_info">
                <view class="img" v-if="masterImg"  @tap="uploadImg">
                    <view class="infoBg">
                            <image class="infoImg"  :src="ossUrl + (masterImg||'')"></image>
                    </view>
                </view>
                <view class="img" v-else  @tap="uploadImg">
                    <image class="addImg" src="/static/tutor/message/icon_add1@2x.png"></image>
                </view>
            </view>
            </view>
        <view class="item_info">
            <view class="label_info">当前定位</view>
            <view class="comp_info">
                <view class="comp_infoSelect" @tap="getAdress">
                    <view class="lt">
                       {{address}}
                    </view>
                    <image class="rt" src="/static/tutor/message/icon_xiala@2x.png"></image>
                </view>
            </view>
        </view>
         <view class="footer">
            <tui-form-button :disabled="saveLoading" :loading="saveLoading" @click="handleConfirm" margin="24rpx 0 0 0"  radius="40rpx" :size="32" color="#fff" width="690rpx" height="84rpx" background="#2FD7D3">
				{{ tutorServiceTitle==='打卡图' ?'开始服务':'结束服务'}}
			</tui-form-button>
         </view>
        </view>
      </view>
    </tui-drawer>
  </template>
  <script>
  export default {
    data() {
      return {
        address:'',
        masterImg:'',
        saveLoading:false,
        latitude:'',
        longitude:''
      };
    },
    props: {
      visible: {
        type: Boolean,
        default: false,
      },
	  tutorServiceTitle:{
		type: String,
        default: '打卡图',
	  },
      top: {
        type: Number,
        default: 0,
      },
      ossUrl:{
        type: String,
        default: '',
      }
    },
    methods: {
      closeDrawer() {
        this.$emit("clear");
      },
       //获取当前定位
        getAdress(){
            this.checkauthorize()
        },
        	// 定位授权
			checkauthorize() {
				let self = this

				// #ifdef MP-WEIXIN
				uni.getSetting({
					success(res) {
						if (!res.authSetting['scope.userLocation']) {
							uni.authorize({
								scope: 'scope.userLocation',
								success: () => { //这里是用户同意授权后的回调
									self.getLocation();
								},
								fail: () => { //这里是用户拒绝授权后的回调
									self.rejectSetting()
								}
							})
						} else { //用户已经授权过了
							self.getLocation();
						}
					}
				})
				// #endif

				// #ifdef APP-PLUS
				// APP端需要先检查权限
				this.checkAppLocationPermission();
				// #endif

				// #ifndef MP-WEIXIN || APP-PLUS
				this.getLocation();
				// #endif
			},

			// 检查APP位置权限
			checkAppLocationPermission() {
				// #ifdef APP-PLUS
				const self = this;
				// 获取当前系统信息
				const systemInfo = uni.getSystemInfoSync();
				// 判断是否是安卓系统
				const isAndroid = systemInfo.platform.toLowerCase() === 'android';

				if (isAndroid) {
					// 安卓平台需要动态申请权限
					const permissions = [
						'android.permission.ACCESS_FINE_LOCATION',
						'android.permission.ACCESS_COARSE_LOCATION'
					];

					plus.android.requestPermissions(
						permissions,
						function(resultObj) {
							// 检查是否有已授权的权限
							let hasLocationPermission = false;
							for (let i = 0; i < resultObj.granted.length; i++) {
								const grantedPermission = resultObj.granted[i];
								if (permissions.includes(grantedPermission)) {
									hasLocationPermission = true;
									break;
								}
							}

							if (hasLocationPermission) {
								// 有位置权限，获取位置
								self.getLocation();
							} else {
								// 没有位置权限，提示用户
								uni.showModal({
									title: '提示',
									content: '需要位置权限才能正常使用应用，请在设置中开启',
									confirmText: '去设置',
									success: function(res) {
										if (res.confirm) {
											// 打开应用设置页面
											self.openAppPermissionSettings();
										}
									}
								});
							}
						},
						function(error) {
							console.error('权限请求失败:', error);
						}
					);
				} else {
					// iOS平台直接请求位置权限
					self.getLocation();
				}
				// #endif
			},

			// 打开应用权限设置页面
			openAppPermissionSettings() {
				// #ifdef APP-PLUS
				if (uni.getSystemInfoSync().platform.toLowerCase() === 'android') {
					// 安卓平台
					const Intent = plus.android.importClass("android.content.Intent");
					const Settings = plus.android.importClass("android.provider.Settings");
					const Uri = plus.android.importClass("android.net.Uri");
					const mainActivity = plus.android.runtimeMainActivity();
					const intent = new Intent();
					intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
					const uri = Uri.fromParts("package", mainActivity.getPackageName(), null);
					intent.setData(uri);
					mainActivity.startActivity(intent);
				} else {
					// iOS平台
					const UIApplication = plus.ios.import("UIApplication");
					const application = UIApplication.sharedApplication();
					const NSURL = plus.ios.import("NSURL");
					const setting = NSURL.URLWithString("app-settings:");
					application.openURL(setting);
					plus.ios.deleteObject(setting);
					plus.ios.deleteObject(NSURL);
					plus.ios.deleteObject(application);
				}
				// #endif
			},

			// 获取当前定位的经纬度
			getLocation() {
				let self = this
				uni.getLocation({
					type: 'gcj02',
					success: function(res) {
						self.latitude = res.latitude;
						self.longitude = res.longitude;
						//经纬度转换成省市区 latitude纬度，long经度
						self.$utils.getAddress(res.latitude, res.longitude,
							'661f987dcae58c7cb089e589ad3c7b18', (obj) => {
								self.address = obj.name;
						});
					},
					fail: (err) => {
						console.error('定位失败:', err);
						// #ifdef APP-PLUS
						// APP端定位失败，可能是权限问题，重新检查权限
						if (uni.getSystemInfoSync().platform.toLowerCase() === 'android') {
							self.checkAppLocationPermission();
						}
						// #endif
					}
				});
			},

			// 用户拒绝授权后的回调 (微信小程序)
			rejectSetting() {
				var that = this;
				uni.showModal({
					title: '警告',
					content: '授权失败，请打开位置消息授权',
					success: (res) => {
						if (res.confirm) { //去授权
							that.toOpenSetting();
						} else if (res.cancel) { //用户点击取消
							console.log(res);
							uni.showModal({
								title: '提示',
								content: '获取权限失败，将无法获取定位哦~',
								showCancel: false,
								success: () => {
									that.toOpenSetting();
								}
							})
						}
					}
				})
			},
			//打开设置页面
			toOpenSetting() {
				// #ifdef MP-WEIXIN
				uni.openSetting({
					success: (e) => {
						console.log(e);
					}
				})
				// #endif

				// #ifdef APP-PLUS
				this.openAppPermissionSettings();
				// #endif
			},
        //拍摄当前照片
			uploadImg(){
				let _this = this;
				uni.showLoading({
					title: '上传中...'
				})
				_this.landscapeShow = true; 
				// 使用通用的选择媒体方法
				_this.$utils.chooseMedia({
					count: 1,
					sizeType: ['original', 'compressed'],
					sourceType: ['camera'], // 必须拍照
					mediaType: ['image']
				}, (res, success) => {  
					if (success) {
					 
						// 选择成功，上传文件
						_this.$utils.uploadFile(res.tempFilePaths[0], (imgInfo) => {
							if (imgInfo.statusCode == 200) {
								let dataImg = JSON.parse(imgInfo.data);
								uni.showToast({
									title: '上传成功',
									icon: 'none',
									duration: 2000
								});
								_this.masterImg = dataImg.data.fileName;
							} else {
								uni.showToast({
									title: '上传失败',
									icon: 'none',
									duration: 2000
								});
							}
							uni.hideLoading();
							_this.landscapeShow = false;
						});
					} else {
						// 选择失败
						uni.hideLoading();
						_this.landscapeShow = false;
					}
				});
			},

      handleConfirm() {
        if(!this.masterImg){
            uni.showToast({
                title: '请上传打卡图',
                icon: 'none',
                duration: 2000
            });
            return false
        }
        if(!this.longitude){
            uni.showToast({
                title: '请获取当前定位',
                icon: 'none',
                duration: 2000
            });
            return false
        }
        this.saveLoading=true
        this.$emit("confirm",{
            masterImg:this.masterImg,
            latitude:this.latitude,
            longitude:this.longitude
        });
      },
    },
  };

  </script>

  <style lang="scss" scoped>
  .container {
    background: #fff;
    border-radius: 24rpx 24rpx 0 0;
    padding: 40rpx;
  }
  .footer{
    display: flex;
    justify-content: center;
    padding-bottom: 40rpx;
  }
  .userInfoEdit_Content{
	 background: #FFFFFF;
	 border-radius: 40rpx 40rpx 0rpx 0rpx;
	 .img_header{
		width:228rpx;
		height:228rpx;
		.img_opt_header{
			width:228rpx;
			height:228rpx;
			overflow: hidden;
			 border: 3rpx solid #2FD7D3;
		}
		.optImg{
			width: 100%;
			height: 100%;
			object-fit: cover;
		}
		.icon_camera{
			width:40rpx;
			height:40rpx;
			position: absolute;
			right: 0;
			bottom:40rpx;
			z-index:10;
		}
	 }
    }
    .form_my{
		padding:0 30rpx;
		.item_info{
			padding-bottom: 40rpx;
			.label_info{
				font-weight: 600;
				font-size: 28rpx;
				color: #333333;
				line-height: 33rpx;
			}
			.rates{
				font-size: 28rpx;
				color: #333333;
			}
			.comp_info{
				padding-top: 30rpx;
				display: flex;
				flex-wrap: wrap;
				align-items: center;
				 justify-content: flex-start;
				 .comp_infoSelect{
					 padding: 22rpx 40rpx;
					 width: 100%;
					 background-color: #FFFEF8;
					 border: 2rpx solid #F3E6D3;
					 border-radius: 16rpx;
					 display: flex;
					 align-items: center;
					 justify-content: space-between;
					 .lt{
						 font-weight: 500;
						 font-size: 28rpx;
						 color: #666666;
						 line-height: 33rpx;
						 text-align: left;
					 }
					 .rt{
						 width: 20rpx;
						 height: 20rpx;
					 }
				 }
				.img{
					width: 156rpx;
					height: 156rpx;
					position: relative;
					margin-right: 22rpx;
					margin-bottom: 22rpx;
					.infoBg{
						width: 156rpx;
						height: 156rpx;
						overflow: hidden;
						border-radius: 16rpx 16rpx 16rpx 16rpx;
						.infoImg{
							width: 100%;
							height: 100%;
							object-fit: cover;
						}
					}

					.delImg{
						width: 16rpx;
						height: 16rpx;
						position: absolute;
						top: 8rpx;
						right: 8rpx;
					}
				}
				.img:last-child{
					margin-right: 0;
				}
				.addImg{
					width: 156rpx;
					height: 156rpx;
				}
			}
		}
	}
  </style>